package externalSort;

import externalSort.Tournament.mergeFileByHuffman;
import externalSort.Tournament.runGenerationManagerByTournamentTree;

import java.io.*;
import java.util.List;

public class Main {

    public static void main(String[] args) throws IOException {
        //清除之前的文件
        fileCleaner.cleanAllExternalSortFiles();
        FileOutputStream fileOutputStream = new FileOutputStream("output1.txt");
        PrintStream printStream = new PrintStream(fileOutputStream);

        // 重定向System.out到文件
        System.setOut(printStream);

        // 参数设置
        String inputFile = "./file/large_input.txt";
        String outputFile = "./file/sorted_output.txt";
        int totalNumbers = 1000000;
        int bufferSize =2000;
        int queueSize=50;
        int generation=2000;
        int maxValue = 100000000;
        int numThreads = 12;
        int k=1024;

        System.out.println("=== 开始多线程外部排序 ===");
        System.out.println("总记录数: " + totalNumbers);
        System.out.println("顺串大小: " + bufferSize);
        System.out.println("使用线程数: " + numThreads);
        try {
            // 1. 生成测试数据
            generateBigFile.generateLargeFile(inputFile, totalNumbers, maxValue);

            long start = System.currentTimeMillis();
            Runtime runtime = Runtime.getRuntime();
            long usedMemBefore = runtime.totalMemory() - runtime.freeMemory();
            // 2. 生成顺串
//            List<String> runFiles = runGenerationManager.run(inputFile,generation,totalNumbers,bufferSize);
            runGenerationManagerByTournamentTree solution=new runGenerationManagerByTournamentTree(k,bufferSize,inputFile);
            List<filePair> runFiles=solution.startRunningGenerations();
            long usedMemAfter = runtime.totalMemory() - runtime.freeMemory();
            long end = System.currentTimeMillis();
            System.out.printf("[Performance] 生成顺串运行时间: %d ms\n", (end - start));
            System.out.printf("[Memory] 生成顺串Used memory: %.2f MB -> %.2f MB\n",
                    usedMemBefore / (1024.0 * 1024.0),
                    usedMemAfter / (1024.0 * 1024.0));
            System.out.printf("[Threads] Active count: %d\n", Thread.activeCount());


//            runGenerationManagerByTournamentTree solution=new runGenerationManagerByTournamentTree(k,bufferSize,inputFile);
//            List<filePair> runFiles=solution.startRunningGenerations();
//            System.out.println(runFiles.size());

//            for(filePair fp:runFiles){
//                System.out.println(fp.cnt);
//            }

            long start2 = System.currentTimeMillis();
            long usedMemBefore2 = runtime.totalMemory() - runtime.freeMemory();
            // 3. 执行归并排序
//            mergeManager mergeManager = new mergeManager(runFiles, outputFile, bufferSize, numThreads,queueSize);
//            String finalFile = mergeManager.executeMerge();
            int mergeWay=3;
            mergeFileByHuffman mergeManager=new mergeFileByHuffman(runFiles,bufferSize,"./file/merge/",mergeWay);

            List<List<filePair>> list=mergeManager.huffman();

            for(List<filePair> list1:list){
                for(filePair fp:list1){
                    System.out.print(fp.name+" "+fp.cnt);
                }
                System.out.print("\n");
            }

            long usedMemAfter2 = runtime.totalMemory() - runtime.freeMemory();
            long end2 = System.currentTimeMillis();
            System.out.printf("[Performance] 归并运行时间: %d ms\n", (end2 - start2));
            System.out.printf("[Memory] 归并Used memory: %.2f MB -> %.2f MB\n",
                    usedMemBefore2 / (1024.0 * 1024.0),
                    usedMemAfter2 / (1024.0 * 1024.0));
            System.out.printf("[Threads] Active count: %d\n", Thread.activeCount());

            String csvLine=String.format("%d,%d,%.1f,%.1f",end-start,end2-start2,usedMemAfter / (1024.0 * 1024.0),usedMemAfter2 / (1024.0 * 1024.0));
            System.out.println(csvLine);
//            PrintWriter writer=new PrintWriter(new FileWriter("./Phase2Performance.csv"),true);
//
//            writer.println(csvLine);
//            writer.flush();

//            System.out.println("归并顺串运行时间: " + (end - start) + " ms");
//
//            start = System.currentTimeMillis();
//
//            mergeFileByHuffman mergeManager=new mergeFileByHuffman(runFiles,bufferSize,"./file/merge/",mergeWay);
//
//            List<String[]> list=mergeManager.huffman();
//            end = System.currentTimeMillis();
//            System.out.println("归并顺串运行时间: " + (end - start) + " ms");
//            for(String[] strs:list){
//                for(String s:strs){
//                    System.out.print(s+" ");
//                }
//                System.out.print("\n");
//            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
